#!/bin/sh

JOB=`basename $1`

cd $1

RENDER_XML=`find . -name yafarayRender.xml`

if [ -z "${RENDER_XML}" ]; then
	#echo "INFO: plugins/render: This is NOT a Yafaray job" >&2
	exit 1
fi

echo "INFO: plugins/render: This is a Yafaray job" >&2

OLD_CASPER_RUN_DIR=$CASPER_RUN_DIR
OLD_NODES_USE=$NODES_USE
OLD_NODES_NUMBER=$NODES_NUMBER

source ${CASPER_CONF_DIR}/casperd.conf

CASPER_RUN_DIR=$OLD_CASPER_RUN_DIR
NODES_USE=$OLD_NODES_USE
NODES_NUMBER=$OLD_NODES_NUMBER

export TEXTURES_PATH=`pwd`/textures/

mkdir log

###################
## PREPARING JOB ##
###################
(
	flock -x 200

	echo jobs $JOB status preparing
	
	# Moving all textures
	TEXTURES=`find . -name '*.png' -or -name '*.jpg' -or -name '*.gif' -or -name '*.tga'`
	mkdir textures
	for texture in $TEXTURES
	do
		if [ $texture != ${TEXTURES_PATH}`basename $texture` ]; then
			mv $texture ${TEXTURES_PATH}`basename $texture`
		fi
	done

	if [ -f ./yafarayRender.xml ]; then
		mv ${RENDER_XML} ./yafarayRender.xml
	fi
	
	${CASPER_BASE_DIR}/plugins/render/yafaray-xml-cut.sh yafarayRender.xml ${NODES_NUMBER} 1 > log/yafaray-xml-cut.log
	EXIT_STATUS=$?
	if [ $EXIT_STATUS -ne 0 ]; then
		exit $EXIT_STATUS
	fi

) 200>${CASPER_RUN_DIR}/slot_prepare.lock

echo jobs $JOB status prepared

CURR_DIR=`pwd`

#####################
## RENDERING IMAGE ##
#####################
(
	flock -x 200
	
	echo jobs $JOB status rendering

	i=0

	for NODE in ${NODES_USE}
	do
		# Manda il pezzo di job
		mkdir result-${NODE}
		rocks run host ${NODES_NAMES[$NODE]} "yafaray-xml ${CURR_DIR}/yafarayRender-${i}.xml -o ${CURR_DIR}/result-${NODE}/ > ${CURR_DIR}/log/${NODES_NAMES[$NODE]}.log" &
		i=$(($i+1))
	done
	
	# Attende la fine di tutti i job inviati
	for NODE in ${NODES_USE}
	do
		wait
		EXIT_STATUS=$?
		if [ $EXIT_STATUS -ne 0 ]; then
			exit $EXIT_STATUS;
		fi
	done
	
) 200>${CASPER_RUN_DIR}/slot_execute.lock

for NODE in ${NODES_USE}
do
	if [ ! -f "${CURR_DIR}/result-${NODE}/yafaray.tga" ]; then
		echo "ERROR: plugins/render/execute.sh: unable to find ${CURR_DIR}/result-${NODE}/yafaray.tga" >&2
		exit 1
	fi
done

echo jobs $JOB status rendered

#########################################
## REBUILDING FINAL IMAGE AND CLEANING ##
#########################################
(
	flock -x 200
	
	echo jobs $JOB status rebuilding
	
	# Rebuilding image
	CMD="convert +append"
	for NODE in ${NODES_USE}
	do
		CMD="$CMD result-$NODE/yafaray.tga"
	done
	$CMD yafaray.tga

	# Cleaning work dir
	rm yafarayRender*
	rm -Rf textures
	for NODE in $NODES_USE
	do
		rm -Rf result-$NODE
	done

	
) 200>${CASPER_RUN_DIR}/slot_finish.lock
